package net.mayee.alice.spring.interceptor;

import jodd.log.Logger;
import jodd.log.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by mayee on 15/10/5.
 */
public class DatatablesAjaxHandlerInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatatablesAjaxHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        request.setCharacterEncoding("UTF-8");
        String reJSON = (String) request.getAttribute("reJSON");
        if(StringUtils.isEmpty(reJSON)){
            LOGGER.error("**** DatatablesAjaxHandlerInterceptor:reJSON is null! ****");
        }

        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-store");
        PrintWriter out = response.getWriter();
        out.write(reJSON);
    }

}
